package base.ctrl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import em.model.SessionVO;
import em.util.CommonTools;
import org.apache.log4j.Logger;

import java.util.*;

/**
 * 基础Controller
 */
public abstract class BaseController extends Controller {

	public Logger log=Logger.getLogger(getClass());
	protected boolean parseJson = false;
	protected Map<String,Object> jsonData=new LinkedHashMap();

	//判断是否开启审核
	public boolean openAuditing(){
		//待完善
		return true;
	}

	/*
	 * 通过sqlKey查询sql语句，并查询出结果，返回List<Record>
	 * strSqlKey格式 如：emp.empList  emp为文件名;empList为emp文件里的一个sql语句的Key值
	 */
	public List<Record> getData(String strSqlKey,Map<String,Object> map){
		List<Record> lst=new ArrayList<Record>();
		String strSql;
		//取得sql
		if(map==null) {
			strSql = CommonTools.getInstance().getSql(strSqlKey);
		}else{
			strSql = CommonTools.getInstance().getSql(strSqlKey, map);
		}
		if(StrKit.isBlank(strSql)) return lst;

		return Db.find(strSql);
	}

	public List<Record> getData(String strSqlKey){
		return getData(strSqlKey,null);
	}

	/**
	 * 取得一条记录
	 * @param strSqlKey
	 * @param map
	 * @return
	 */
	public Record getFirstData(String strSqlKey,Map<String,Object> map){
		List<Record> lst= getData(strSqlKey,map);
		return lst.size()>0?lst.get(0):null;
	}

	// 取得权限
	public void getPrivilegeList(){
		if (getRequest().getSession()!=null){
			this.renderJson("{\"privilegeList\":"+((SessionVO)getRequest().getSession().getAttribute("SessionVO")).getPrivilegeList()+"}");
		}else{
			this.renderJson("{\"privilegeList\":[]}");
		}
	}

	public String getPara(String name) {
		parseJson();
		if(jsonData.containsKey(name) && CommonTools.getInstance().notBlank(jsonData.get(name))){
			return jsonData.get(name).toString().replace("'","").replace("--","");
		}
		return null;
	}
	public String getPara(String name, String defaultValue) {
		String value = getPara(name);
		return StrKit.notBlank(value) ? value : defaultValue;
	}

	public Integer getParaToInt(String name) {
		return getParaToInt(name,null);
	}
	public Integer getParaToInt(String name, Integer defaultValue) {
		String value = getPara(name);
		if (StrKit.isBlank(value))
			return defaultValue;
		if (value.startsWith("N") || value.startsWith("n"))
			return -Integer.parseInt(value.substring(1));
		return Integer.parseInt(value);
	}

	public Boolean getParaToBoolean(String name) {
		return getParaToBoolean(name,null);
	}
	public Boolean getParaToBoolean(String name, Boolean defaultValue) {
		String value = getPara(name);
		if (StrKit.isBlank(value)) {
			if(defaultValue==null) throw new RuntimeException("Can not parse the parameter \"" + value + "\" to boolean value.");
			return defaultValue;
		}
		value = value.trim();
		if ("1".equals(value) || "true".equals(value))
			return Boolean.TRUE;
		else if ("0".equals(value) || "false".equals(value))
			return Boolean.FALSE;
		throw new RuntimeException("Can not parse the parameter \"" + value + "\" to boolean value.");
	}

	public Long getParaToLong(String name) {
		return getParaToLong(name,null);
	}
	public Long getParaToLong(String name, Long defaultValue) {
		String value =getPara(name);
		if (StrKit.isBlank(value))
			return defaultValue;
		if (value.startsWith("N") || value.startsWith("n"))
			return -Long.parseLong(value.substring(1));
		return Long.parseLong(value);
	}

	public JSONArray getParaToArr(String name){
		parseJson();
		if (jsonData.containsKey(name)) {
			Object obj = jsonData.get(name);
			if (obj instanceof JSONArray){
				return (JSONArray) obj;
			}
		}
		return null;
	}

	public List<Map<String, Object>> getParaToList(String name){
		parseJson();
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		JSONObject json;
		Map<String,Object> jsonMap;
		if (jsonData.containsKey(name)) {
			JSONArray jsonArr=getParaToArr(name);
			if(jsonArr!=null){
				Iterator<Object> it = jsonArr.iterator();
				while(it.hasNext()){
					json = (JSONObject) it.next();
					jsonMap = new HashMap<String,Object>();
					for(Object k : json.keySet()){
						jsonMap.put(k.toString(), json.get(k));
					}
					list.add(jsonMap);
				}
			}
		}
		return list;
	}

	@SuppressWarnings("rawtypes")
	public Map<String, Object> getParas(){
		parseJson();
		Map<String, Object> paras = new HashMap<String, Object>();
		if (jsonData!=null && jsonData.size()>0) {
			for(Object k : jsonData.keySet()){
				Object v = jsonData.get(k);
				if(v instanceof String[]){
					paras.put(k.toString(),Arrays.toString((String[])v));
				}else if(v instanceof String) {
					//if(!"".equals(v.toString().trim()))
					paras.put(k.toString(),"".equals(v.toString().trim())?null:v.toString().trim());
				}else{
					paras.put(k.toString(),CommonTools.getInstance().isBlank(v)?null:v);
				}
			}
		}
		return paras;
	}

	protected void parseJson(){
		if (!parseJson){
			Enumeration<String> e = this.getRequest().getParameterNames();
			while (e.hasMoreElements()) {
				String ename = e.nextElement();
				jsonData.put(ename,this.getRequest().getParameter(ename));
//				if(StrKit.notBlank(ename.replace("\"",""))) {
//					if (ename.startsWith("{") || ename.startsWith("\"")) {
//						JSONObject json = JSON.parseObject(ename);
//						for (Object k : json.keySet()) {
//							jsonData.put(k.toString(), CommonTools.getInstance().notBlank(json.get(k))?json.get(k):null);
//						}
//					} else {
//						jsonData.put(ename, this.getRequest().getParameter(ename));
//					}
//				}
			}
			if(this.getSessionAttr("SessionVO")!=null){
				SessionVO vo=this.getSessionAttr("SessionVO");
				jsonData.put("GlobalAccType",vo.getAccType());
				jsonData.put("GlobalOrgId",vo.getOrgId());
				jsonData.put("GlobalAccId",vo.getAccountId());
				jsonData.put("GlobalCompany",vo.getCompany());
				jsonData.put("GlobalOrgType",vo.getOrgType());
			}
			parseJson = true;
		}
	}

	/**
	 * 是否存在Key值
	 * @param name
	 * @return
	 */
	protected boolean isHaveKey(String name){
		parseJson();
		if(parseJson){
			if(jsonData!=null && jsonData.containsKey(name)){
				return true;
			}
		}
		return false;
	}
}
